<template>
  <div>
    <div class="search">
      <!-- <span class="iconfont">&#xe632;</span> -->
      <input type="text" v-model="keyword" class="search-input" placeholder="输入城市景点">
    </div>
    <div class="search-content" ref="warpper" v-show="keyword">
      <ul>
        <li
          class="search-item border-bottom"
          @click="handleCityClick(item.name)"
          v-for="item of list"
          :key="item.id"
        >{{item.name}}</li>
        <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from "better-scroll";
import { mapMutations } from "vuex";

export default {
  name: "CitySearch",
  props: {
    cities: Object
  },
  data() {
    return {
      keyword: "",
      list: [],
      timer: null
    };
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      console.log("key:" + this.keyword);
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        let result = [];
        for (let i in this.cities) {
          this.cities[i].forEach(value => {
            if (
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              result.push(value);
            }
          });
        }
        this.list = result;
      }, 100);
    }
  },
  mounted() {
    //使用了better-scroll，默认它会阻止touch事件。所以在配置中需要加上click: true
    this.scroll = new BScroll(this.$refs.warpper, {
      mouseWheel: false,
      click: true,
      tap: true
    });
  },
  computed: {
    hasNoData() {
      return !this.list.length;
    }
  },
  methods: {
    handleCityClick(city) {
      // this.$store.dispatch('changeCity',city);// 组件通过Actions 调用Commit
      //this.$store.commit("changeCity", city); //通过vuex直接调用Commit
      this.changeCity(city); //通过map Mutations 映射调用
      this.$router.push("/"); //路由页面跳转
    },
    ...mapMutations(["changeCity"]) //将vuex -> Mutations中的changeCity方法映射到当前组件
  }
};
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.search {
  height: 0.72rem;
  padding: 0 0.1rem;
  background-color: $bgColor;

  .search-input {
    box-sizing: border-box;
    width: 100%;
    height: 0.62rem;
    padding: 0 0.1rem;
    line-height: 0.62rem;
    background: #fff;
    text-align: center;
    border-right: 0.1rem;
    color: #666;
  }
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #eee;

  .search-item {
    text-align: left;
    line-height: 0.62rem;
    padding-left: 0.2rem;
    background: #fff;
    color: #666;
  }

  .border-bottom {
    &:before {
      border-color: #ccc;
    }
  }
}
</style>